package com.sample.tcp;

import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.TimeUnit;

import com.swak.Constants;
import com.swak.OS;
import com.swak.exception.RemotingException;
import com.swak.reactivex.threads.Contexts;
import com.swak.reactivex.transport.Channel;
import com.swak.reactivex.transport.ExchangeChannel;
import com.swak.reactivex.transport.ExchangeHandlerAdapter;
import com.swak.reactivex.transport.ExchangeServer;
import com.swak.reactivex.transport.Exchangers;
import com.swak.reactivex.transport.TransportMode;
import com.swak.reactivex.transport.resources.LoopResources;
import com.swak.registry.URL;
import com.swak.utils.Maps;

/**
 * 这是一款比较通用的基于 TCP 的通信服务
 * 
 * @author 618lf
 */
public class Server extends ExchangeHandlerAdapter {

	private LoopResources resources = Contexts.createEventLoopResources(TransportMode.OS, 1, 2, "Test.EventLoop-",
			false, 2, TimeUnit.SECONDS);

	ExchangeServer server;
	URL url;

	public Server() throws RemotingException {
		Map<String, String> parameters = Maps.newHashMap();
		parameters.put(Constants.Bind_Host, Constants.ANYHOST);
		this.url = new URL("Test", OS.ip(), 10889, parameters);
		this.server = Exchangers.bind(url, resources, this);
	}

	@Override
	public void received(Channel channel, Object message) throws RemotingException {

	}

	@Override
	public CompletionStage<Object> reply(ExchangeChannel channel, Object message) throws RemotingException {
		return CompletableFuture.completedFuture(message);
	}

	@Override
	public void caught(Channel channel, Throwable exception) throws RemotingException {
		super.caught(channel, exception);
	}

	public static void main(String[] args) throws RemotingException {
		new Server();
	}
}
